<?php

/*

    -101 环境配置不合法 $prod
    -102 token不合法 $tk
    -103 msg不合法
    -201 写队列失败dev
    -202 写队列失败
    -301 DB连接失败
    -302 数据库失败
    -900 域名不合法

*/

    require_once("../include/def.php");
    require_once(INCLUDE_DIR."functions.php");
    require_once(INCLUDE_DIR."DBHelperi_applepie.class.php");

    function push_redis_dev($msg_enc)
    {
        $red = new Redis();
        $red->connect( '172.20.28.147', 9980, 1 );
        $key = 'msgq';
        $r = $red->rpush($key, $msg_enc);
        if ($r)
        {
            if (DEBUG) mylog('PUSH WRITE QUEUE SUCC WITH NEW LENGTH: '.$r, LOGFN_DEBUG);
            msgexit('+OK');
        }
        else
        {
            if (DEBUG) mylog('PUSH REDIS QUEUE FAILED: '.$msg_enc, LOGFN_DEBUG);
            msglogexit(-201, LOGFN_ACCESS_ERROR);
        }
    }

    function push_redis($msg_enc)
    {
        // TODO 临时直接写 redis queue
        $red = new Redis();
        $red->connect( '172.20.28.147', 11920, 1 );
        $key = 'msgq';
        $r = $red->rpush($key, $msg_enc);
        if ($r)
        {
            if (DEBUG) mylog('PUSH WRITE QUEUE SUCC WITH NEW LENGTH: '.$r, LOGFN_DEBUG);
            msgexit('+OK');
        }
        else
        {
            if (DEBUG) mylog('PUSH REDIS QUEUE FAILED: '.$msg_enc, LOGFN_DEBUG);
            msglogexit(-202, LOGFN_ACCESS_ERROR);
        }
    }

    function write_db(&$msg, $env)
    {
/*
CREATE TABLE `msg` (
  `id` bigint(20) unsigned NOT NULL,
  `prod` int(10) unsigned NOT NULL,
  `token` char(64) NOT NULL,
  `content` varchar(200) NOT NULL,
  `mid` varchar(50) NOT NULL,
  `badge` int(10) unsigned NOT NULL,
  `sound` varchar(100) NOT NULL,
  `image` varchar(100) NOT NULL,
  `expire` int(10) unsigned NOT NULL,
  `title` varchar(100) NOT NULL,
  `custom` varchar(200) NOT NULL,
  `tmr` double(14,4) NOT NULL,
  `tms` double(14,4) NOT NULL,
  `tm` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `errmsg` blob NOT NULL,
  `hoststr` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
*/
        $db = new DBHelperi_applepie($env);

        $token = $db->realEscapeString($msg['tk']);
        $content = $db->realEscapeString($msg['content']);
        $mid = $db->realEscapeString($msg['mid']);
        $sound = $db->realEscapeString($msg['sound']);
        $image = $db->realEscapeString($msg['image']);
        $title = $db->realEscapeString($msg['title']);
        $custom = $db->realEscapeString($msg['custom']);
        $sql = "INSERT INTO msg (id, prod, token, content, mid, badge, sound, image, expire, title, custom, tmr)"
            ." VALUES "
            ." ({$msg['id']}, {$msg['server']['prod']}, '$token', '$content', '$mid',"
            ."  {$msg['badge']}, '$sound', '$image', {$msg['expire']}, '$title',"
            ."  '$custom', {$msg['tmr']})";
        $r = $db->query($sql);
        if (!$r)
        {
            while (!$r and $db->errno() == 1062)
            {
                if (DEBUG) mylog('DB msg id key duplicate: '.$msg['id'], LOGFN_DEBUG);
                $msg['id']++;
                $sql = "INSERT INTO msg (id, prod, token, content, mid, badge, sound, image, expire, title, custom, tmr)"
                    ." VALUES "
                    ." ({$msg['id']}, {$msg['server']['prod']}, '$token', '$content', '$mid',"
                    ."  {$msg['badge']}, '$sound', '$image', {$msg['expire']}, '$title',"
                    ."  '$custom', {$msg['tmr']})";
                $r = $db->query($sql);
            }

            if (!$r and $db->errno() != 1062)
            {
                $t = 'Query Error (' . $db->errno() . ') '. $db->errstr();
                mylog('DB QUERY FAILED: '.$t, LOGFN_ACCESS_ERROR);
                if (DEBUG) mylog('DB QUERY FAILED: '.$t, LOGFN_DEBUG);
                msglogexit(-302, LOGFN_ACCESS_ERROR);
            }
        }
        $db->disconnect();

        return true;
    }

    // 环境
    $prod = isset($_GET['prod']) ? (int)$_GET['prod'] : 0;
    if (!$prod or !in_array($prod, array_keys($prods))) msglogexit(-101, LOGFN_ACCESS_ERROR);

    $msg = array('server' => $prods[$prod]);
    if (!$msg['server']) msglogexit(-101, LOG_ACCESS_ERROR);

    // token
    $msg['tk'] = isset($_GET['tk']) ? $_GET['tk'] : '';
    if (!$msg['tk'] or strlen($msg['tk'])!=64) msglogexit(-102, LOGFN_ACCESS_ERROR);

    // 内容
    $msg['content'] = isset($_GET['content']) ? urldecode($_GET['content']) : '';
    if (!$msg['content'] or strlen($msg['content'])>=200) msglogexit(-103, LOGFN_ACCESS_ERROR);

    // 自定义ID
    $msg['mid'] = isset($_GET['mid']) ? urldecode($_GET['mid']) : '';

    // Badge
    $msg['badge'] = isset($_GET['badge']) ? (int)$_GET['badge'] : 0;

    // sound
    $msg['sound'] = isset($_GET['sound']) ? urldecode($_GET['sound']) : '';

    // image
    $msg['image'] = isset($_GET['image']) ? urldecode($_GET['image']) : '';

    // 过期时间
    $msg['expire'] = isset($_GET['expire']) ? (int)$_GET['expire'] : 30;

    // 标题
    $msg['title'] = isset($_GET['title']) ? urldecode($_GET['title']) : '';

    // 自定义字段
    $msg['custom'] = isset($_GET['custom']) ? urldecode($_GET['custom']) : '';


    if (isset($_GET['urionly'])) msgexit('http://'.$_SERVER["HTTP_HOST"].$_SERVER['REQUEST_URI']);

    // 接收时间
    $msg['tmr'] = microtime(true);
    $msg['id'] = floor($msg['tmr'] * 10000);

    if ($_SERVER["HTTP_HOST"] == 'pncp.dev')        // 测试环境写 db
    {
        write_db($msg, 'DEV');
    }
    elseif ($_SERVER["HTTP_HOST"] == 'applepie')    // 生产环境写 db
    {
        write_db($msg, 'PRO');
    }
    else
    {
        if (DEBUG) mylog('FAILED domain name -900: '.$msg_enc, LOGFN_DEBUG);
        msglogexit(-900, LOGFN_ACCESS_ERROR);
    }

    $msg_enc = json_encode($msg);
    if (DEBUG) mylog('PUSH RECEIVED REQUEST: '.$msg_enc, LOGFN_DEBUG);


    if ($_SERVER["HTTP_HOST"] == 'pncp.dev')        // 测试环境写 msg queue
    {
        push_redis_dev($msg_enc);
    }
    elseif ($_SERVER["HTTP_HOST"] == 'applepie')    // 生产环境写 msg queue
    {
        push_redis($msg_enc);
    }
    else
    {
        if (DEBUG) mylog('FAILED domain name -900: '.$msg_enc, LOGFN_DEBUG);
        msglogexit(-900, LOGFN_ACCESS_ERROR);
    }


    exit;
?>